<template>
  <div class="favorites">
    <div class="page-header">
      <el-page-header @back="goBack">
        <template #content>
          <h1 class="page-title">
            <el-icon><StarFilled /></el-icon>
            我的收藏
          </h1>
        </template>
      </el-page-header>
    </div>

    <div v-loading="loading" class="favorites-content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 景点收藏 -->
        <el-tab-pane label="景点收藏" name="attractions">
          <div v-if="favorites.length > 0" class="favorites-grid">
            <el-card
              v-for="attraction in favorites"
              :key="attraction.id"
              class="favorite-card"
              shadow="hover"
              @click="goToDetail(attraction)"
            >
          <div class="card-image">
            <LazyImage
              v-if="attraction.primary_image"
              :src="getImageUrl(attraction.primary_image)"
              :preview-src-list="[getImageUrl(attraction.primary_image)]"
              fit="cover"
              height="200"
              image-class="attraction-image"
            />
            <div v-else class="no-image">
              <el-icon><PictureRounded /></el-icon>
              <span>暂无图片</span>
            </div>
            <div class="card-badge">
              <el-tag :type="getCategoryType(attraction.category)" size="small">
                {{ attraction.category_display || '文化古迹' }}
              </el-tag>
            </div>
          </div>

          <div class="card-content">
            <h3 class="card-title">{{ attraction.name }}</h3>
            <div class="card-info">
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span class="text-ellipsis">{{ attraction.address || '暂无地址' }}</span>
              </div>
              <div class="info-item">
                <el-icon><Money /></el-icon>
                <span>¥{{ attraction.ticket_price }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ attraction.visit_time || 60 }}分钟</span>
              </div>
            </div>
            <div class="card-footer">
              <div class="rating-section">
                <el-rate
                  :model-value="attraction.rating / 1"
                  disabled
                  size="small"
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </div>
            </div>
          </div>

          <div class="card-actions" @click.stop>
            <el-button
              type="primary"
              size="small"
              :icon="ViewIcon"
              @click="goToDetail(attraction)"
            >
              详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="StarFilled"
              @click="removeFavorite(attraction)"
              :loading="removingAttractions[attraction.id]"
            >
              取消收藏
            </el-button>
            </div>
          </el-card>
        </div>

        <el-empty v-else description="暂无收藏的景点" :image-size="200">
          <el-button type="primary" @click="goToAttractions">去探索景点</el-button>
        </el-empty>
        <div v-if="canLoadMoreFavorites" style="text-align:center; margin-top: 16px;">
          <el-button @click="loadMoreFavorites" :loading="loading">加载更多</el-button>
        </div>
        </el-tab-pane>

        <!-- 路线收藏 -->
        <el-tab-pane label="路线收藏" name="routes">
          <div v-loading="routesLoading">
            <div v-if="favoriteRoutes.length > 0" class="routes-grid">
              <el-card
                v-for="route in favoriteRoutes"
                :key="route.id"
                class="route-favorite-card"
                shadow="hover"
                @click="viewRoute(route)"
              >
                <div class="route-card-header">
                  <h3>{{ route.start_attraction?.name || '路线规划' }}</h3>
                  <el-tag v-if="route.is_shared" type="success" size="small">已分享</el-tag>
                </div>
                <el-descriptions :column="2" size="small" border>
                  <el-descriptions-item label="起始景点">
                    {{ route.start_attraction?.name || '未知' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="预算">
                    ¥{{ route.budget }}
                  </el-descriptions-item>
                  <el-descriptions-item label="总费用">
                    ¥{{ route.total_cost }}
                  </el-descriptions-item>
                  <el-descriptions-item label="总距离">
                    {{ route.total_distance }} 公里
                  </el-descriptions-item>
                  <el-descriptions-item label="景点数量">
                    {{ route.optimal_route?.route?.length || 0 }} 个
                  </el-descriptions-item>
                  <el-descriptions-item label="收藏时间">
                    {{ formatTime(route.created_at) }}
                  </el-descriptions-item>
                </el-descriptions>
                <div class="route-card-footer">
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="viewRoute(route)"
                  >
                    查看详情
                  </el-button>
                  <el-button
                    v-if="route.share_code"
                    type="success"
                    size="small"
                    @click.stop="viewSharedRoute(route.share_code)"
                  >
                    查看分享
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="StarFilled"
                    @click.stop="removeRouteFavorite(route)"
                    :loading="removingRoutes[route.id]"
                  >
                    取消收藏
                  </el-button>
                </div>
              </el-card>
        </div>
            <el-empty v-else description="暂无收藏的路线" :image-size="200">
              <el-button type="primary" @click="goToRoutePlan">去规划路线</el-button>
            </el-empty>
            <div v-if="canLoadMoreRoutes" style="text-align:center; margin-top: 16px;">
              <el-button @click="loadMoreRoutes" :loading="routesLoading">加载更多</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  PictureRounded,
  Location,
  Money,
  Clock,
  View as ViewIcon,
  StarFilled,
  MapLocation
} from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import LazyImage from '../components/LazyImage.vue'
import logger from '../utils/logger'
import { getImageUrl as getImageUrlUtil } from '../utils/apiConfig'

export default {
  name: 'Favorites',
  components: {
    PictureRounded,
    Location,
    Money,
    Clock,
    LazyImage
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const routesLoading = ref(false)
    const favorites = ref([])
    const favoriteRoutes = ref([])
    const favoritesPage = ref(1)
    const favoritesPageSize = ref(12)
    const favoritesTotal = ref(0)
    const routesPage = ref(1)
    const routesPageSize = ref(10)
    const routesTotal = ref(0)
    const removingAttractions = ref({})
    const removingRoutes = ref({})
    const activeTab = ref('attractions')

    const isAuthenticated = computed(() => store.getters.isAuthenticated)

    const fetchFavorites = async () => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }

      loading.value = true
      try {
        const data = await TravelAPI.getFavoriteAttractions({ page: favoritesPage.value, page_size: favoritesPageSize.value })
        favoritesTotal.value = data?.count ?? (data?.results?.length || 0)
        const results = data?.results || []
        if (favoritesPage.value === 1) {
          favorites.value = results
        } else {
          favorites.value = favorites.value.concat(results)
        }
      } catch (error) {
        logger.error('获取收藏列表失败:', error)
        ElMessage.error('获取收藏列表失败')
      } finally {
        loading.value = false
      }
    }

    const getImageUrl = (url) => {
      return getImageUrlUtil(url)
    }

    const getCategoryType = (category) => {
      const types = {
        'cultural': 'warning',
        'natural': 'success',
        'modern': 'info',
        'food': 'danger'
      }
      return types[category] || 'info'
    }

    const goToDetail = (attraction) => {
      router.push(`/attractions/${attraction.id}`)
    }

    const removeFavorite = async (attraction) => {
      try {
        await ElMessageBox.confirm(
          `确定要取消收藏"${attraction.name}"吗？`,
          '确认取消收藏',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        removingAttractions.value[attraction.id] = true
        try {
          await TravelAPI.toggleFavorite(attraction.id, false)
          favorites.value = favorites.value.filter(f => f.id !== attraction.id)
          ElMessage.success('已取消收藏')
        } catch (error) {
          logger.error('取消收藏失败:', error)
          ElMessage.error(error.response?.data?.error || '取消收藏失败')
        } finally {
          removingAttractions.value[attraction.id] = false
        }
      } catch (error) {
        // 用户取消
      }
    }

    const goBack = () => {
      router.back()
    }

    const goToAttractions = () => {
      router.push('/attractions')
    }

    // 获取收藏的路线
    const fetchFavoriteRoutes = async () => {
      if (!isAuthenticated.value) {
        return
      }

      routesLoading.value = true
      try {
        const response = await TravelAPI.getFavoriteRoutes({ page: routesPage.value, page_size: routesPageSize.value })
        routesTotal.value = response?.count ?? (response?.results?.length || 0)
        const results = response?.results || []
        if (routesPage.value === 1) {
          favoriteRoutes.value = results
        } else {
          favoriteRoutes.value = favoriteRoutes.value.concat(results)
        }
      } catch (error) {
        logger.error('获取收藏路线列表失败:', error)
        ElMessage.error('获取收藏路线列表失败')
      } finally {
        routesLoading.value = false
      }
    }

    const canLoadMoreFavorites = computed(() => favorites.value.length < favoritesTotal.value)
    const canLoadMoreRoutes = computed(() => favoriteRoutes.value.length < routesTotal.value)

    const loadMoreFavorites = async () => {
      if (loading.value || !canLoadMoreFavorites.value) return
      favoritesPage.value += 1
      await fetchFavorites()
    }

    const loadMoreRoutes = async () => {
      if (routesLoading.value || !canLoadMoreRoutes.value) return
      routesPage.value += 1
      await fetchFavoriteRoutes()
    }

    // 查看路线详情
    /**
     * 查看路线详情（从分页历史中查询）
     * @param {Object} route - 路线对象
     */
    const viewRoute = async (route) => {
      try {
        const historyData = await TravelAPI.getRouteHistory({ page_size: 50 })
        const routes = historyData.results || historyData || []
        const foundRoute = routes.find(r => r.id === route.id)
        if (foundRoute && foundRoute.share_code) {
          router.push(`/route-share/${foundRoute.share_code}`)
        } else {
          router.push({
            path: '/route-plan',
            query: {
              start_attraction_id: route.start_attraction?.id,
              budget: route.budget
            }
          })
        }
      } catch (error) {
        logger.error('获取路线信息失败:', error)
        ElMessage.error('获取路线信息失败')
      }
    }

    // 查看分享的路线
    const viewSharedRoute = (shareCode) => {
      router.push(`/route-share/${shareCode}`)
    }

    // 取消收藏路线
    const removeRouteFavorite = async (route) => {
      try {
        await ElMessageBox.confirm(
          `确定要取消收藏这条路线吗？`,
          '确认取消收藏',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        removingRoutes.value[route.id] = true
        try {
          await TravelAPI.toggleRouteFavorite(route.id, false) // false表示取消收藏
          favoriteRoutes.value = favoriteRoutes.value.filter(r => r.id !== route.id)
          ElMessage.success('已取消收藏')
        } catch (error) {
          logger.error('取消收藏失败:', error)
          ElMessage.error(error.response?.data?.error || '取消收藏失败')
        } finally {
          removingRoutes.value[route.id] = false
        }
      } catch (error) {
        // 用户取消
      }
    }

    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 标签页切换
    const handleTabChange = (tabName) => {
      if (tabName === 'routes' && favoriteRoutes.value.length === 0) {
        routesPage.value = 1
        fetchFavoriteRoutes()
      }
      if (tabName === 'attractions' && favorites.value.length === 0) {
        favoritesPage.value = 1
        fetchFavorites()
      }
    }

    const goToRoutePlan = () => {
      router.push('/route-plan')
    }

    onMounted(() => {
      favoritesPage.value = 1
      routesPage.value = 1
      fetchFavorites()
    })

    return {
      loading,
      favorites,
      removingAttractions,
      isAuthenticated,
      getImageUrl,
      getCategoryType,
      goToDetail,
      removeFavorite,
      goBack,
      goToAttractions,
      activeTab,
      favoriteRoutes,
      routesLoading,
      removingRoutes,
      fetchFavoriteRoutes,
      viewRoute,
      viewSharedRoute,
      removeRouteFavorite,
      formatTime,
      handleTabChange,
      goToRoutePlan,
      PictureRounded,
      Location,
      Money,
      Clock,
      ViewIcon,
      StarFilled,
      MapLocation,
      favoritesPage,
      favoritesPageSize,
      favoritesTotal,
      routesPage,
      routesPageSize,
      routesTotal,
      canLoadMoreFavorites,
      canLoadMoreRoutes,
      loadMoreFavorites,
      loadMoreRoutes
    }
  }
}
</script>

<style scoped>
.favorites {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.favorites-content {
  margin-top: 20px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.favorite-card {
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid rgba(200, 16, 46, 0.12);
  background: linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(227,242,253,0.85) 100%);
  backdrop-filter: blur(12px);
  box-shadow: 0 4px 20px rgba(200, 16, 46, 0.08), 0 1px 3px rgba(0, 0, 0, 0.05);
  position: relative;
}

.favorite-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.favorite-card:hover {
  transform: translateY(-6px) scale(1.01);
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.15), 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: rgba(212, 175, 55, 0.4);
}

.favorite-card:hover::before {
  opacity: 1;
}

.card-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.attraction-image {
  width: 100%;
  height: 100%;
}

.image-slot,
.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #909399;
}

.card-badge {
  position: absolute;
  top: 10px;
  right: 10px;
}

.card-content {
  padding: 15px;
}

.card-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(135deg, #303133 0%, #606266 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.favorite-card:hover .card-title {
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  transform: translateX(2px);
}

.card-info {
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 5px;
  font-size: 14px;
  color: #606266;
}

.info-item .el-icon {
  margin-right: 5px;
  color: #909399;
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.card-footer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.rating-section {
  margin-bottom: 10px;
}

.card-actions {
  padding: 10px 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 10px;
}

.card-actions .el-button {
  flex: 1;
}

/* 路线收藏卡片样式 */
.routes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
}

.route-favorite-card {
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid rgba(200, 16, 46, 0.12);
  background: linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(227,242,253,0.85) 100%);
  backdrop-filter: blur(12px);
  box-shadow: 0 4px 20px rgba(200, 16, 46, 0.08), 0 1px 3px rgba(0, 0, 0, 0.05);
  position: relative;
}

.route-favorite-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #C8102E 0%, #D4AF37 50%, #1E88E5 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.route-favorite-card:hover {
  transform: translateY(-6px) scale(1.01);
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.15), 0 4px 8px rgba(0, 0, 0, 0.1);
  border-color: rgba(212, 175, 55, 0.4);
}

.route-favorite-card:hover::before {
  opacity: 1;
}

.route-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 16px;
  border-bottom: 1px solid rgba(200, 16, 46, 0.1);
  margin-bottom: 16px;
}

.route-card-header h3 {
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
  transition: all 0.3s ease;
}

.route-favorite-card:hover .route-card-header h3 {
  transform: translateX(2px);
}

.route-card-footer {
  display: flex;
  gap: 12px;
  padding: 16px 20px 20px;
  justify-content: flex-end;
  border-top: 1px solid rgba(200, 16, 46, 0.08);
  margin-top: 16px;
  flex-wrap: wrap;
}

.route-card-footer .el-button {
  transition: all 0.3s ease;
  min-width: 100px;
}

.route-card-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(200, 16, 46, 0.2);
}
</style>







